package com.dollama.random.model.impl;


import com.dollama.random.model.BookModel;
import com.dollama.random.model.entity.Book;
import com.dollama.random.model.remote.RetrofitService;
import com.dollama.random.ui.view.RandomView;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by tony on 2017/5/4.
 */

public class BookModelImpl implements BookModel {
    @Override
    public void getBookInfo(String bookName, final RandomView randomView) {
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("https://api.douban.com/v2/")
//                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
//                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.douban.com/v2/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//支持RxJava
                .build();

        RetrofitService service = retrofit.create(RetrofitService.class);
//        Call<Book> call =  service.getSearchBook("Head%20First%20Servlet%20JSP", null, 0, 1);
//        call.enqueue(new Callback<Book>() {
//            @Override
//            public void onResponse(Call<Book> call, Response<Book> response) {
////                text.setText(response.body()+"");
//                randomView.setRandomResult(response.body()+"");
//            }
//            @Override
//            public void onFailure(Call<Book> call, Throwable t) {
//            }
//        });
        Observable<Book> observable =  service.getSearchBook("Head%20First%20Servlet%20JSP", null, 0, 1);
        observable.subscribeOn(Schedulers.io())//请求数据的事件发生在io线程
                .observeOn(AndroidSchedulers.mainThread())//请求完成后在主线程更显UI
                .subscribe(new Observer<Book>() {//订阅
                    @Override
                    public void onCompleted() {
                        //所有事件都完成，可以做些操作。。。
                    }
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace(); //请求过程中发生错误
                    }
                    @Override
                    public void onNext(Book book) {//这里的book就是我们请求接口返回的实体类
                        randomView.setRandomResult(book.toString());
                    }
                });

    }
}
